{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c6bd44e0-8852-4146-881f-0a4f328ba5fc",
   "metadata": {},
   "source": [
    "# ChatCompletion模型开发指南"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "outputs": [],
   "source": [
    "from openai import OpenAI\n",
    "client = OpenAI()\n",
    "\n",
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n",
    "    {\"role\": \"user\", \"content\": \"Who won the world series in 2020?\"},\n",
    "    {\"role\": \"assistant\", \"content\": \"The Los Angeles Dodgers won the World Series in 2020.\"},\n",
    "    {\"role\": \"user\", \"content\": \"Where was it played?\"}\n",
    "  ]\n",
    ")"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "outputs": [
    {
     "data": {
      "text/plain": "ChatCompletion(id='chatcmpl-9AY82xQ7PAzW2hU9tjF1FFXH8LTRg', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='The 2020 World Series was played at Globe Life Field in Arlington, Texas.', role='assistant', function_call=None, tool_calls=None))], created=1712301498, model='gpt-3.5-turbo-0125', object='chat.completion', system_fingerprint='fp_b28b39ffa8', usage=CompletionUsage(completion_tokens=17, prompt_tokens=53, total_tokens=70))"
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "markdown",
   "id": "6a389157-805b-42ea-a522-f1937d4a06f8",
   "metadata": {},
   "source": [
    "## 1. ChatCompletion API使用方法"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "811ef114-f0b6-4b3a-9aff-a6e17fbf3002",
   "metadata": {
    "tags": []
   },
   "source": [
    "ChatCompletion.create的使用方法和Completion.create非常类似，整体函数使用流程和核心参数都非常类似，这里我们直接对Chat模型提问“什么是AI大模型？”提问和获取结果流程如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "dfbeb497-6e91-4a8f-892a-40d65c998a46",
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": "SyncPage[Model](data=[Model(id='gpt-3.5-turbo-16k', created=1683758102, object='model', owned_by='openai-internal'), Model(id='gpt-3.5-turbo-16k-0613', created=1685474247, object='model', owned_by='openai'), Model(id='whisper-1', created=1677532384, object='model', owned_by='openai-internal'), Model(id='davinci-002', created=1692634301, object='model', owned_by='system'), Model(id='gpt-3.5-turbo', created=1677610602, object='model', owned_by='openai'), Model(id='dall-e-2', created=1698798177, object='model', owned_by='system'), Model(id='tts-1-hd-1106', created=1699053533, object='model', owned_by='system'), Model(id='tts-1-hd', created=1699046015, object='model', owned_by='system'), Model(id='text-embedding-3-large', created=1705953180, object='model', owned_by='system'), Model(id='gpt-3.5-turbo-instruct-0914', created=1694122472, object='model', owned_by='system'), Model(id='gpt-3.5-turbo-instruct', created=1692901427, object='model', owned_by='system'), Model(id='gpt-3.5-turbo-0301', created=1677649963, object='model', owned_by='openai'), Model(id='gpt-3.5-turbo-0613', created=1686587434, object='model', owned_by='openai'), Model(id='tts-1', created=1681940951, object='model', owned_by='openai-internal'), Model(id='dall-e-3', created=1698785189, object='model', owned_by='system'), Model(id='gpt-3.5-turbo-1106', created=1698959748, object='model', owned_by='system'), Model(id='babbage-002', created=1692634615, object='model', owned_by='system'), Model(id='tts-1-1106', created=1699053241, object='model', owned_by='system'), Model(id='text-embedding-3-small', created=1705948997, object='model', owned_by='system'), Model(id='text-embedding-ada-002', created=1671217299, object='model', owned_by='openai-internal'), Model(id='gpt-3.5-turbo-0125', created=1706048358, object='model', owned_by='system')], object='list')"
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "#old  openai0.28版本后已经调整了openai的使用方式\n",
    "#import openai\n",
    "#openai.api_key = os.getenv(\"OPENAI_API_KEY\")\n",
    "#openai.Model.list()\n",
    "\n",
    "# new\n",
    "from openai import OpenAI\n",
    "client = OpenAI(\n",
    "  api_key=os.environ['OPENAI_API_KEY'],  # this is also the default, it can be omitted\n",
    ")\n",
    "client.models.list()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "616d8ee2-0ff5-4f11-abc2-c446d07b78d8",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"user\", \"content\": \"请问，什么是AI大模型？\"}\n",
    "  ]\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "912adbf1-16f8-4119-903d-623fab041ac1",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": "ChatCompletion(id='chatcmpl-9AXF9T4lURXaU2S4ElFycQpeDHiDQ', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='AI大模型是指具有庞大参数数量和复杂结构的人工智能模型。这些模型通常通过深度学习技术训练，并在各种任务中取得了良好的性能表现。AI大模型的例子包括大规模神经网络如BERT、GPT等。这些模型通常需要大量的计算资源和数据来训练，并在自然语言处理、计算机视觉、语音识别等领域中得到广泛应用。', role='assistant', function_call=None, tool_calls=None))], created=1712298095, model='gpt-3.5-turbo-0125', object='chat.completion', system_fingerprint='fp_b28b39ffa8', usage=CompletionUsage(completion_tokens=145, prompt_tokens=19, total_tokens=164))"
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "60312d02-b2dd-429c-95e2-6aefe928170b",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": "'OpenAI是一家非营利人工智能研究实验室，旨在推动人工智能技术的发展，并确保人工智能对人类的利益产生积极影响。OpenAI致力于开发开源的人工智能技术，以促进人工智能领域的创新和发展。该实验室的研究重点包括深度学习、强化学习、自然语言处理、计算机视觉等领域。对于AI行业来说，OpenAI是一个具有推动作用的领先机构，旨在通过共享研究成果和开源技术，促进全球范围内的合作与创新。'"
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查看第一个返回结果的message\n",
    "response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21b09d75-7652-412b-aca4-f00162111b90",
   "metadata": {},
   "source": [
    "在获取对话结果的过程中，除了ChatCompletion.create返回结果最终是保存在message属性中（Completion.create返回结果是保存在text属性中），\n",
    "其他方面ChatCompletion.create的返回结果和Completion.create返回结果完全一致。而文本补全模型需要输入“prompt”，输出结果是“text”；\n",
    "而对话模型需要输入“message”，返回也是“message”，可以说这种文本交互形式确实非常符合人类在进行聊天时的问答习惯。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "0b265916-2d21-49e5-bc97-ed6df22fc8c8",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": "260"
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查看消耗的tokens数\n",
    "response.usage.total_tokens"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0bd35d6e-f4f3-4232-a0fb-d72a56574f00",
   "metadata": {},
   "source": [
    "## 2. ChatCompletion API参数详解"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68a0ca78-7ced-4be0-b14c-879363134d6f",
   "metadata": {},
   "source": [
    "### 2.1 API参数说明"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58a2fe79-61df-4039-a72e-42d841e215c0",
   "metadata": {
    "tags": []
   },
   "source": [
    "关于ChatCompletion.create函数的详细参数解释，可以在官网相关页面查阅：https://platform.openai.com/docs/api-reference/chat/create 。\n",
    "能够发现，和Completion.create函数相比，ChatCompletion.create函数的参数结构发生了以下变化：\n",
    "1. 用messages参数代替了prompt参数，使之更适合能够执行对话类任务；\n",
    "2. 新增functions和function_call参数，使之能够在函数内部调用其他工具的API，该功能为0613新增功能；\n",
    "3. 其他核心参数完全一致，\n",
    "4. 剔除了best_of参数，即Chat模型不再支持从多个答案中选择一个最好的答案这一功能；"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93e80fc8-acf5-4fe8-bec7-ba535fb078d5",
   "metadata": {
    "tags": []
   },
   "source": [
    "所以核心需要解释的就是三个参数：messages参数、functions和function_call参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "3c2c0135-f5da-47bd-89f6-f7f1e35ae145",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "messages=[\n",
    "    {\"role\": \"user\", \"content\": \"请问什么是AI大模型？\"}\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "add894e7-9629-46c7-beef-721f8f945ef8",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<OpenAIObject at 0x1346d3ce270> JSON: {\n",
       "  \"role\": \"assistant\",\n",
       "  \"content\": \"AI\\u5927\\u6a21\\u578b\\u6307\\u7684\\u662f\\u5177\\u6709\\u5de8\\u5927\\u53c2\\u6570\\u6570\\u91cf\\u548c\\u8ba1\\u7b97\\u8d44\\u6e90\\u9700\\u6c42\\u7684\\u4eba\\u5de5\\u667a\\u80fd\\u6a21\\u578b\\u3002\\u5b83\\u662f\\u7531\\u6570\\u767e\\u4e07\\u751a\\u81f3\\u6570\\u5341\\u4ebf\\u7684\\u53c2\\u6570\\u7ec4\\u6210\\u7684\\u795e\\u7ecf\\u7f51\\u7edc\\u6a21\\u578b\\uff0c\\u901a\\u5e38\\u9700\\u8981\\u5927\\u89c4\\u6a21\\u5e76\\u884c\\u8ba1\\u7b97\\u5e73\\u53f0\\u7684\\u652f\\u6301\\u6765\\u8fdb\\u884c\\u8bad\\u7ec3\\u548c\\u63a8\\u65ad\\u3002AI\\u5927\\u6a21\\u578b\\u5177\\u6709\\u66f4\\u5f3a\\u7684\\u5b66\\u4e60\\u548c\\u63a8\\u7406\\u80fd\\u529b\\uff0c\\u80fd\\u591f\\u5904\\u7406\\u66f4\\u590d\\u6742\\u7684\\u4efb\\u52a1\\uff0c\\u5e76\\u5728\\u8bed\\u8a00\\u7406\\u89e3\\u3001\\u56fe\\u50cf\\u8bc6\\u522b\\u3001\\u81ea\\u7136\\u8bed\\u8a00\\u5904\\u7406\\u7b49\\u9886\\u57df\\u5c55\\u73b0\\u51fa\\u66f4\\u9ad8\\u7684\\u6027\\u80fd\\u3002\\u8fd9\\u7c7b\\u6a21\\u578b\\u53ef\\u4ee5\\u901a\\u8fc7\\u5927\\u89c4\\u6a21\\u6570\\u636e\\u96c6\\u8fdb\\u884c\\u9884\\u8bad\\u7ec3\\uff0c\\u5e76\\u901a\\u8fc7\\u5fae\\u8c03\\u3001\\u8fc1\\u79fb\\u5b66\\u4e60\\u7b49\\u65b9\\u6cd5\\u9002\\u5e94\\u7279\\u5b9a\\u7684\\u4efb\\u52a1\\u3002\"\n",
       "}"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "f9e2da8e-09e8-4d41-aac2-699bbcfab96e",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'AI大模型指的是具有巨大参数数量和计算资源需求的人工智能模型。它是由数百万甚至数十亿的参数组成的神经网络模型，通常需要大规模并行计算平台的支持来进行训练和推断。AI大模型具有更强的学习和推理能力，能够处理更复杂的任务，并在语言理解、图像识别、自然语言处理等领域展现出更高的性能。这类模型可以通过大规模数据集进行预训练，并通过微调、迁移学习等方法适应特定的任务。'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63adeff9-87ae-44f3-a3fd-2b6b8139cc38",
   "metadata": {},
   "source": [
    "对话Chat模型的每个对话任务都是通过输入和输出message来完成的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c08ddc87-ed8d-4fd6-9203-25ca017855a9",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "## messages可以包含多条信息，但模型只会对于最后一条用户信息进行回答\n",
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"user\", \"content\": \"请问什么是 AI 大模型？\"},\n",
    "    {\"role\": \"user\", \"content\": \"请问什么是图像大模型？\"}\n",
    "  ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "da6aab01-2642-4328-85bd-f4b9d6f95981",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<OpenAIObject chat.completion id=chatcmpl-8FLZcb7D03k6Hq6Cbu1eVNZhiypAT at 0x1346d3cdb50> JSON: {\n",
       "  \"id\": \"chatcmpl-8FLZcb7D03k6Hq6Cbu1eVNZhiypAT\",\n",
       "  \"object\": \"chat.completion\",\n",
       "  \"created\": 1698668540,\n",
       "  \"model\": \"gpt-3.5-turbo-0613\",\n",
       "  \"choices\": [\n",
       "    {\n",
       "      \"index\": 0,\n",
       "      \"message\": {\n",
       "        \"role\": \"assistant\",\n",
       "        \"content\": \"\\u56fe\\u50cf\\u5927\\u6a21\\u578b\\u662f\\u6307\\u5177\\u6709\\u5de8\\u5927\\u53c2\\u6570\\u91cf\\u548c\\u590d\\u6742\\u7ed3\\u6784\\u7684\\u4eba\\u5de5\\u667a\\u80fd\\u6a21\\u578b\\uff0c\\u7528\\u4e8e\\u56fe\\u50cf\\u8bc6\\u522b\\u3001\\u56fe\\u50cf\\u751f\\u6210\\u548c\\u56fe\\u50cf\\u5904\\u7406\\u7b49\\u4efb\\u52a1\\u3002\\u8fd9\\u4e9b\\u6a21\\u578b\\u901a\\u5e38\\u662f\\u57fa\\u4e8e\\u6df1\\u5ea6\\u5b66\\u4e60\\u65b9\\u6cd5\\u6784\\u5efa\\u7684\\uff0c\\u5e76\\u901a\\u8fc7\\u5927\\u89c4\\u6a21\\u6570\\u636e\\u96c6\\u8fdb\\u884c\\u8bad\\u7ec3\\u3002\\u4e0e\\u4f20\\u7edf\\u7684\\u5c0f\\u6a21\\u578b\\u76f8\\u6bd4\\uff0c\\u56fe\\u50cf\\u5927\\u6a21\\u578b\\u5177\\u6709\\u66f4\\u5f3a\\u7684\\u5b66\\u4e60\\u80fd\\u529b\\u548c\\u66f4\\u9ad8\\u7684\\u51c6\\u786e\\u6027\\uff0c\\u53ef\\u4ee5\\u5904\\u7406\\u66f4\\u590d\\u6742\\u7684\\u56fe\\u50cf\\u4efb\\u52a1\\u3002\\u7136\\u800c\\uff0c\\u7531\\u4e8e\\u5176\\u53c2\\u6570\\u91cf\\u5e9e\\u5927\\uff0c\\u56fe\\u50cf\\u5927\\u6a21\\u578b\\u5728\\u8bad\\u7ec3\\u548c\\u63a8\\u65ad\\u8fc7\\u7a0b\\u4e2d\\u5bf9\\u8ba1\\u7b97\\u8d44\\u6e90\\u7684\\u9700\\u6c42\\u4e5f\\u5f88\\u9ad8\\u3002\"\n",
       "      },\n",
       "      \"finish_reason\": \"stop\"\n",
       "    }\n",
       "  ],\n",
       "  \"usage\": {\n",
       "    \"prompt_tokens\": 35,\n",
       "    \"completion_tokens\": 165,\n",
       "    \"total_tokens\": 200\n",
       "  }\n",
       "}"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "919a31e0-9126-4a26-9b25-a4949006e102",
   "metadata": {
    "tags": []
   },
   "source": [
    " assistant消息和user消息是一一对应的"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "02deedd3-7bf7-4788-8930-181d3af5130d",
   "metadata": {
    "tags": []
   },
   "source": [
    "user和assistant的这种提问方式尽管足够清晰，但往往形式上不够丰富，例如在实践中人们发现，给聊天机器人进行一个身份设置，\n",
    "其实是非常有效的引导模型创作我们想要的结果的方法，例如如果我们希望获得一个关于“什么是AI 大模型？”更加严谨且丰富的答案，我们可以以“假设你是\n",
    "一名资深的AI大模型专家”为模型进行身份设置，例如我们可以以如下方式向模型进行提问："
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2fc0c9c3-8219-4583-8294-4cf7920ed369",
   "metadata": {},
   "source": [
    "### 2.2 message之设定角色 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "a653f0ca-f0af-4afa-92f2-4ceb57f29f1b",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"user\", \"content\": \"假设你是一名AI大模型资深专家，请帮我回答，什么是AI是什么？\"}\n",
    "  ]\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "f5b477c0-cc73-4b72-8320-d0d838641cd3",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": "'AI是人工智能的简称，它是一种模拟人类智能行为的技术。AI系统可以学习、推理、规划、识别图像和语音等任务，并根据所学知识和算法进行决策。AI技术可以模拟人类的思维过程，帮助解决各种复杂的问题和挑战。AI的发展已经深刻影响了我们的生活和工作方式，带来了诸如无人驾驶、语音识别、智能推荐等先进的应用。'"
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1192351-f42b-421a-9d0a-7dbed6e40718",
   "metadata": {
    "tags": []
   },
   "source": [
    "此时模型的回答就变得更加详细和严谨，更像一名“专家”的语气风格，也同时说明我们对模型进行的身份设定是切实有效的。\n",
    "那我们就可以直接给用户设定身份"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "b57cc77e-8f58-41ec-b6bd-5d5c4e423832",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"system\", \"content\": \"你是一名AI大模型资深专家\"},\n",
    "    {\"role\": \"user\", \"content\": \"请问什么是AI大模型？\"}\n",
    "  ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "3e127989-4f8d-4362-8859-6f36cdadd687",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": "'AI大模型通常指的是参数数量庞大、参数规模庞大的人工智能模型，常常包括数百万到数十亿个参数。这些模型通常经过深度学习训练，能够在多个领域展现出强大的性能，比如自然语言处理、计算机视觉、语音识别等。由于参数规模巨大，这些模型需要庞大的计算资源和数据来进行训练，且通常需要运行在多个GPU或者TPU等高性能计算设备上才能发挥其潜力。近年来，随着计算能力的提升和算法的改进，AI大模型的应用范围也在不断扩大。'"
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14756087-ebf4-407c-ae70-49e2897fac90",
   "metadata": {},
   "source": [
    "能够看出，这里我们在原有消息之前，新增一条消息{\"role\": \"system\", \"content\": \"你是一名AI大模型资深专家\"}，也能起到设定模型身份的作用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "899517d3-e1a5-4b05-a329-587057de538d",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"system\", \"content\": \"你是一名的脱口秀演员\"},\n",
    "    {\"role\": \"user\", \"content\": \"请问什么是AI大模型？\"}\n",
    "  ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "fae10dcb-a499-4d02-b430-22a22b4eec81",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'嘿，AI大模型指的是使用人工智能技术训练的庞大模型，通常具有巨大的参数量和极高的计算资源需求。这些模型可以在各种任务中展现出惊人的能力，如自然语言处理、图像识别、语音识别等。一些知名的AI大模型包括GPT-3（生成式预训练模型）和BERT（双向编码器表示器）等。这些模型通过大量的训练数据和复杂的模型结构，使得它们可以以前所未有的方式理解和生成内容。当然，由于其巨大的计算需求，训练和部署大型AI模型也带来了挑战和成本。'"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "de12aa88-4385-463f-a415-635f50c22582",
   "metadata": {},
   "source": [
    "### 2.3 message之文本补全"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "de9faa4f-5e12-4554-a26a-e052e31f4483",
   "metadata": {},
   "source": [
    "当messages中只包含一条system消息时，系统会围绕system进行回答，只不过此时系统的assistant的应答消息则更像是一个completion的过程，\n",
    "即围绕system的prompt进行进一步的文本补全"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "e527fb48-0ef9-46f0-b218-47e0efcb10d3",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"system\", \"content\": \"你是一名的脱口秀演员\"},\n",
    "  ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "13cedc7a-000b-42f7-a3e9-3e420b17979f",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": "'嗨！大家好，我是今天的主持人。感谢大家的到场，让我来为大家带来一些欢乐和笑声。今天有没有什么话题是你们特别想要聊的呢？放心，我会为大家带来最新最有趣的段子和笑话。废话不多说，让我们开始今天的表演吧！希望大家尽情享受！'"
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d00c5c8f-b1c1-437b-a717-66093398cf83",
   "metadata": {},
   "source": [
    "### 2.4 message之消息顺序"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea05c5c1-64ed-4053-8354-5809444efe3c",
   "metadata": {
    "tags": []
   },
   "source": [
    "第三方面需要注意的是，如果我们需要根据system系统信息对系统进行设置，然后再提问，那么先system消息再user消息的顺序就变得非常重要，\n",
    "例如还是上面的例子，还是希望以喜剧演员的身份介绍机器学习，但我们调换了system消息和user消息的顺序，那么会发现，system消息的作用就会失效："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "ffb16cfb-b0d6-482a-9b02-1d66b63ed89d",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"user\", \"content\": \"请问什么是AI大模型？\"},\n",
    "    {\"role\": \"system\", \"content\": \"你是一名脱口秀演员\"}\n",
    "  ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "449c4df8-5779-49a1-bb01-78e233127ca1",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'AI大模型是指具有大规模参数和复杂结构的人工智能模型。这些模型通常由深度学习算法训练得到，通过处理大量数据来学习和预测复杂的模式和关系。AI大模型在自然语言处理、图像识别、语音识别等领域取得了重大突破，如GPT-3、BERT等。这些大模型的规模通常以参数数量计量，可以有数亿、甚至数百亿的参数。由于规模庞大，AI大模型需要强大的计算资源和算法支持，能够执行复杂的计算任务。'"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message['content']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e74cac00-6b5d-4be5-901b-928b81095d2b",
   "metadata": {},
   "source": [
    "通过灵活的messages参数，能够非常便捷高效的实现诸多类型的对话需求，例如基于提示词模板的提问、Few-shot提问、基于某背景知识的提问等"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da286a6b-3b9b-4a39-9cd2-d35c2ad921c8",
   "metadata": {},
   "source": [
    "### 2.5 message之Few-shot效果演示"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "9f4e49af-87f3-498f-b043-209aaf7e480f",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "Q1 = '小米有6个气球，她又买了3袋，每袋有10个气球，请问她现在总共有多少个气球？'\n",
    "A1 = '现在小米总共有36个气球。'\n",
    "Q2 = '小明总共有10个苹果，吃了3个苹果，然后又买了5个苹果，请问现在小明总共有多少个苹果？'\n",
    "A2 = '现在小明总共有12个苹果。'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "176d2809-0125-4975-a108-29158fcd6c41",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"user\", \"content\": Q1},\n",
    "    {\"role\": \"assistant\", \"content\": A1},\n",
    "    {\"role\": \"user\", \"content\": Q2}\n",
    "  ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "7a5fa345-a004-4532-a9e8-d56231a6c8b5",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": "'现在小明总共有12个苹果。'"
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4342e906-790a-4be3-8f04-e321f7de35b4",
   "metadata": {},
   "source": [
    "而相比单独进行Q2的提问，经过Few-shot的提示回答的结果，会更加接近A1结果的表示格式："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "f68140db-1cde-4cbb-8a5d-dc2c0c86d48e",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": "'现在小明总共有12个苹果。'"
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "## 可以把提示示例写进一条system信息中，作为当前问答的背景信息\n",
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"system\", \"content\": '问题: ' + Q1 + '答案: ' + A1},\n",
    "    {\"role\": \"user\", \"content\": '问题: ' + Q2 }\n",
    "  ]\n",
    ")\n",
    "response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e25db1c-dcc3-41e4-a55a-0cc183761e53",
   "metadata": {},
   "source": [
    "### 2.6 message之Zero-shot-CoT效果"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fef25143-c177-47fc-a49c-53ac0667f511",
   "metadata": {
    "tags": []
   },
   "source": [
    "即然system消息能够作为背景设定的基本消息并对后续的问答消息造成影响，那么很容易想到的system消息的一个应用场景就是借助system role输入提示模板，\n",
    "为了更好的提高模型推理能力，我们可以在每个prompt中加入一句“请一步步推理并得出结论”进而实现Zero-shot-CoT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "b4c64a21-aa63-4429-bc14-020a0f66ad7d",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "prompt_temp_cot = '请一步步思考并解决问题'\n",
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"system\", \"content\": prompt_temp_cot},\n",
    "    {\"role\": \"user\", \"content\": Q1}\n",
    "  ]\n",
    ")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "1f16eccd-0339-4fe9-bcd3-47c59d4c1183",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": "'首先，小米原本有6个气球，然后买了3袋气球，每袋有10个。所以现在她有：\\n6 + 3 * 10 = 6 + 30 = 36 个气球\\n\\n所以，小米现在总共有36个气球。'"
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "91328885-0a41-4fc9-a4ea-2479749a5299",
   "metadata": {
    "tags": []
   },
   "source": [
    "### 2.7 message之设置聊天背景"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ff1779b-85e9-48f5-aa60-455381c250cf",
   "metadata": {
    "tags": []
   },
   "source": [
    "借助system role设置聊天背景信息，实现类似根据本地知识库回答问题的方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "b32e5204-3536-415e-9112-47a8d1afe3d4",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "text = '冬瓜老师，男，1988年9月16日出生于广东省深圳市 \\\n",
    "        2011年毕业于深圳大学计算机专业。\\\n",
    "        毕业后进入ABC科技公司工作了6年，专注于AI方面的研究，'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "976e173f-7c55-4778-9776-24eb93a55ea8",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"system\", \"content\": text},\n",
    "    {\"role\": \"user\", \"content\": '请问冬瓜老师出生于哪儿？'}\n",
    "  ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "c1d235ce-b139-47a3-8186-c793b189c771",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": "'冬瓜老师出生于广东省深圳市。'"
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message.content"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e937f28-2f5d-4709-b149-4240ef4f2c82",
   "metadata": {},
   "source": [
    "### 2.8 message之多轮对话效果"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ec0d81f-4f4e-4bdd-887e-2e61d6e1e9e3",
   "metadata": {
    "tags": []
   },
   "source": [
    "借助.append方法进行多轮对话，对于Chat模型来说，我们只需要将模型返回的message消息+用户新的提问message拼接到模型的messages参数中，并再次\n",
    "向模型进行提问，即可非常便捷的实现多轮对话。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "21f64a29-33ff-46b9-9f9f-c989d7427f1f",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "openai.openai_object.OpenAIObject"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 使用to_dict()方法将模型返回的message信息转化为字典类型\n",
    "type(response.choices[0].message)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "e8f28bd1-3656-42f5-b42f-e3d9b4692ff5",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'role': 'assistant', 'content': '西瓜老师出生于云南省大理市。'}"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message.to_dict()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "787b862e-a43b-405b-8034-3a2b218281f2",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "messages.append(response.choices[0].message.to_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "7d6dea51-38c2-4ffe-9c73-420f1d92b25f",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 此时messages参数就包含了最开始的问题+问题答案。接下来我们在messages消息中添加下一个问题：\n",
    "messages.append({'role': 'user', 'content': '请问我刚才的问题是？'})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "7c18ac9d-dac8-4ab5-a181-8e48de4112e6",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'role': 'user', 'content': '请问什么是AI大模型？'},\n",
       " {'role': 'assistant', 'content': '西瓜老师出生于云南省大理市。'},\n",
       " {'role': 'user', 'content': '请问我刚才的问题是？'}]"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "messages"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebd6d537-d039-4b36-af91-b9c248de8d12",
   "metadata": {
    "tags": []
   },
   "source": [
    "## 3. 基于知识库的多轮对话机器人案例"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e6fe94de-cc4e-4c57-9f5c-86c7880cdff2",
   "metadata": {
    "tags": []
   },
   "source": [
    "利用Chat模型进行多轮对话，若要构建一个本地知识库问答系统，一个直观且易于实施的策略是：首先让大模型浏览本地知识库内容，\n",
    "并将其设定为System role的知识背景。有了这个背景，模型就能进行基于此知识库的问答。可以这样做：\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8cc1322-f57b-4175-abb4-09a490761e28",
   "metadata": {},
   "source": [
    "### 1. 测试大模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "ac1c8f2f-500b-4dd4-8a20-791f6480ac7d",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"system\", \"content\": \"null\"},\n",
    "    {\"role\": \"user\", \"content\": '你知道《消失的她》的电影里角色有哪些吗？'}\n",
    "  ]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "abc84494-ce43-4599-b253-2aa5e2c545d2",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'《消失的她》这部电影的角色有：\\n1. 稻田瑞希（主角，一个失去记忆的女主人公）\\n2. 野泽大志（男主角，稻田瑞希的男朋友）\\n3. 内田雅也（瑞希的记忆中的前男友）\\n4. 内田雅也的母亲\\n5. 足立（内田雅也的朋友）\\n6. 柿崎（稻田瑞希的朋友）\\n7. 远藤（内田雅也的朋友）\\n8. 小林（内田雅也的朋友）\\n9. 长谷川（内田雅也的朋友）\\n10. 森川（内田雅也的朋友）'"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.choices[0].message['content']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f7e819b6-dcc1-439b-bc8e-6da1c03d6c56",
   "metadata": {},
   "source": [
    "### 2. 读取本地知识库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "edccb4cd-6ace-41e2-a726-4399aba08570",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "with open('消失的她.txt', 'r', encoding='utf-8') as f:\n",
    "    chatCompletion_kg= f.read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "f42de5fd-d5a6-434b-8298-5a2d92913202",
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'《消失的她》是一部充满悬疑和心理刺激的电影，讲述了丈夫何非的妻子李木子在结婚周年旅行中神秘失踪的故事。随后，出现了一个陌生女人冒充李木子，引发了一系列扑朔迷离的事件。以下是对该电影的详细解读：\\n\\n\\n剧情介绍与发展：\\n\\n电影一开始，丈夫何非报警称妻子李木子在国外旅行中突然失踪。然而，当警方介入调查后，情况变得异常复杂。一方面，陌生女人自称是李木子，并提供了身份证明和其他证据。另一方面，何非坚持认为这个女人并非自己的妻子。情节中呈现了众多的矛盾和谜团，让观众猜测真相。\\n\\n主要角色及其设定：\\n\\n何非（朱一龙饰）：失踪的妻子李木子的丈夫，他在失去妻子后竭尽全力寻找她。但他的神秘过去和心理问题让人产生怀疑，观众对他的真实性格和动机产生质疑。\\n\\n李木子（文咏珊饰）：消失的女主角，她在故事初期被认为是何非的妻子。然而，随着故事发展，她的真实身份和行为逐渐显露，让观众对她产生疑虑。\\n\\n陈麦（倪妮饰）：一名金牌律师，卷入了这起失踪案件中。她对案件产生浓厚兴趣，主动接手此案，并不断解密真相。她的出现为故事注入了更多的悬疑元素。\\n\\n林梅（黄子琪饰）：陈麦安排的替身女人，她是受害者之一。她与陈麦合作，试图揭示真相并向何非复仇。\\n\\n悬疑和心理刺激：\\n\\n电影的悬疑元素令人着迷。观众在故事中跟随何非、陈麦和李木子之间错综复杂的关系，推理和猜测真相。每个角色都有着不为人知的秘密和动机，令观众陷入扑朔迷离的氛围。随着剧情的发展，一层层真相被揭示，每一个细节都引发观众的疑虑和惊讶。\\n\\n同时，电影还探讨了人性、道德和正义等主题。何非的精神问题、李木子的复杂人格、陈麦的正义感，以及林梅等受害者的复仇心理，都使得故事更加丰富和引人深思。\\n\\n主题和意义：\\n\\n《消失的她》除了讲述一起失踪案件的悬疑故事，也强调了女性之间的团结与互助。陈麦和林梅是受害者的代表，她们联合其他受害者，通过巧妙的计划揭露何非的罪行，最终让他受到应有的惩罚。这展现了女性的力量和智慧，体现了女性在面对困境时的勇气和决心。\\n\\n同时，电影也警示人们珍惜生命中的幸福和美好时刻，对自己的行为负责，并追求自己的梦想。正义和尊严是电影所强调的核心价值观。\\n\\n综上所述，《消失的她》是一部充满悬疑和反转的电影，通过精心构建的剧情、角色设定和悬念设置，吸引观众的注意力并让他们对真相充满好奇。影片的主题也深刻探讨了女性的力量、正义和珍惜生命的价值观。这些元素共同构成了这部引人入胜的电影。'"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chatCompletion_kg"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "86c02e18-3e4a-4ea2-9e44-9838355b095e",
   "metadata": {},
   "source": [
    "### 3. 问答测试"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "4f94cf57-d9cb-4306-8d17-c55e0fe8358c",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'当然，我可以告诉你《消失的她》电影中的一些角色:\\n\\n1. 何非：失踪妻子李木子的丈夫，由朱一龙饰演。\\n2. 李木子：消失的女主角，由文咏珊饰演。\\n3. 陈麦：一名金牌律师，卷入了这起失踪案件中，由倪妮饰演。\\n4. 林梅：陈麦安排的替身女人，试图向何非复仇，由黄子琪饰演。\\n5. 警方角色：包括调查此案的警察，有助于解锁真相。\\n6. 其他受害者：在剧情中，还会出现其他受害者，一起与陈麦揭示真相。\\n\\n以上是一些电影中的主要角色，他们的行动和个性将推动剧情的发展，并引发观众的好奇心和猜测。'"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response = client.chat.completions.create(\n",
    "  model=\"gpt-3.5-turbo\",\n",
    "  messages=[\n",
    "    {\"role\": \"system\", \"content\": chatCompletion_kg},\n",
    "    {\"role\": \"user\", \"content\": '你知道《消失的她》的电影里角色有哪些吗？'}\n",
    "  ]\n",
    ")\n",
    "\n",
    "response.choices[0].message['content']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7971e4ac-4064-4b39-9394-8af87efe3f82",
   "metadata": {},
   "source": [
    "### 4. 添加多轮对话效果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "e3297f19-db62-4729-a236-2c445d29a5d5",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def chat_with_model(messages):\n",
    "    response = client.chat.completions.create(\n",
    "        model=\"gpt-3.5-turbo\",\n",
    "        messages=messages\n",
    "    )\n",
    "    return response.choices[0].message['content']\n",
    "\n",
    "# 测试函数\n",
    "def gpt_chat_with_model():\n",
    "    # 初始问候\n",
    "    messages = [\n",
    "        {\"role\": \"system\", \"content\": chatCompletion_kg}, ##添加本地知识库\n",
    "        {\"role\": \"user\", \"content\": \"你好！\"},\n",
    "        {\"role\": \"assistant\", \"content\": \"你好！我是一个AIGC智能助理，有什么问题我可以帮助你？\"}\n",
    "    ]\n",
    "    print(chat_with_model(messages))\n",
    "\n",
    "    # 进行对话\n",
    "    while True:\n",
    "        user_input = input(\"用户：\")\n",
    "        messages.append({\"role\": \"user\", \"content\": user_input})\n",
    "        assistant_response = chat_with_model(messages)\n",
    "        messages.append({\"role\": \"assistant\", \"content\": assistant_response})\n",
    "        print(\"助理：\" + assistant_response)\n",
    "\n",
    "        # 判断是否结束对话\n",
    "        if user_input.lower() == 'quit':\n",
    "            break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "e9abed4d-f411-4237-81b3-f7668a948ac1",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你好！我是一个AIGC智能助理，有什么问题我可以帮助你？\n"
     ]
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "用户： 《消失的她》这部电影有哪些角色？\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "助理：《消失的她》这部电影中有几个主要角色，下面是对他们的详细介绍：\n",
      "\n",
      "1. 何非（朱一龙饰演）：主角之一，李木子失踪的丈夫。他是一个神秘而复杂的人物，过去的经历和心理问题使人产生质疑，他坚持认为冒充妻子的女人并不是真正的李木子。\n",
      "\n",
      "2. 李木子（文咏珊饰演）：主角之一，失踪的女主角。她原本被认为是何非的妻子，但随着剧情的发展，她的真实身份和行为逐渐显露，让观众产生疑虑。\n",
      "\n",
      "3. 陈麦（倪妮饰演）：一名金牌律师，卷入了这起失踪案件中。她对案件产生浓厚兴趣，主动接手此案，并不断解密真相。她的出现为故事注入了更多的悬疑元素。\n",
      "\n",
      "4. 林梅（黄子琪饰演）：陈麦安排的替身女人，她是受害者之一。她与陈麦合作，试图揭示真相并向何非复仇。\n",
      "\n",
      "除了这些主要角色，还有其他一些次要角色出现在电影中，如警察、家人和其他被卷入事件中的人物，为故事的发展增加了更多的戏剧张力。\n"
     ]
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "用户： 《消失的她》这个电影的主题是什么？\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "助理：《消失的她》这部电影有几个主要的主题：\n",
      "\n",
      "1. 悬疑和心理刺激：电影通过复杂的情节和角色关系，带给观众充满悬疑和扑朔迷离的故事。观众跟随着何非、陈麦和李木子之间错综复杂的关系，推理和猜测真相。每个角色都有着不为人知的秘密和动机，令观众陷入紧张和充满谜团的氛围中。\n",
      "\n",
      "2. 女性之间的团结与互助：电影中，陈麦和林梅代表了受害者的力量，她们联合其他受害者，通过巧妙的计划揭露何非的罪行，最终让他受到应有的惩罚。这展现了女性的力量和智慧，强调了女性在面对困境时的勇气和决心。\n",
      "\n",
      "3. 正义和尊严：电影中探讨了正义和尊严的重要性。何非的精神问题、李木子的复杂人格、陈麦的追求正义以及林梅等受害者的复仇心理都使得故事更加丰富和引人深思。电影强调了人们应当珍惜生命中的幸福和美好时刻，并为自己的行为负责，追求自己的梦想。\n",
      "\n",
      "综上所述，《消失的她》既是一部充满悬疑和反转的电影，又强调了女性之间的团结与互助以及正义和尊严的重要性。这些主题共同构成了电影的核心思想。\n"
     ]
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "用户： quit\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "助理：好的，如果你还有其他问题，随时可以找我。希望能再次为你提供帮助！再见！\n"
     ]
    }
   ],
   "source": [
    "gpt_chat_with_model()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c04cb185-1f53-4fbe-a0b5-353c9a1f4e50",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
